<?php

namespace app\common\logic;

use app\admin\logic\content\sensitive\Sensitive;
use app\admin\logic\system\Config as SystemConfig;
use app\admin\model\content\sensitive\SensitiveRecord;
use app\common\exception\LogicException;
use app\common\model\ShareCode;
use app\common\validate\Common as CommonValidate;
use app\course\logic\base\Course;
use app\user\tools\tencent\Share;
use app\school\logic\school\{School, SchoolSplitConfig};
use app\topic\logic\Topic;
use app\user\logic\teacher\Teacher;
use think\exception\ValidateException;
use DfaFilter\SensitiveHelper;
use think\facade\Db;
use think\facade\Request;

/**
 * 公共逻辑
 */
class Common
{
    // 分享信息
    public function shareInfo($param): array
    {
        // 验证数据
        try {
            validate(CommonValidate::class)->scene('share_info')->check($param);
        } catch (ValidateException $e) {
            throw new LogicException($e->getError());
        }
        //
        $type         = $param['type'];
        $id           = $param['id'];
        $promo        = $param['promotion'] ?? 0;
        $mid          = request()->mid;
        $host         = request()->mhm_sdn ? request()->mhm_host : request()->pc_host;
        $share_config = SystemConfig::get('share.config', []);
        $share_code   = $this->shortStr($mid . '_' . $type . '_' . $id);

        $uri = [
            1  => '/pageCourse/course/details?id=' . $id . '&share_code=' . $share_code,
            // 2  => '/pages/news/details?id=' . $id,
            2  => '/pageFound/topic/details?id=' . $id,
            11 => '/pageCourse/course/promotion/pintuan?id=' . $promo . '&share_code=' . $share_code,
            12 => '/pageCourse/course/promotion/bargain?id=' . $promo . '&share_code=' . $share_code,
        ];

        switch ($type) {
            case 1:
            case 11:
            case 12:
                $share_key  = 'course';
                $course     = app(Course::class)->where('id', $id)->with(['cover_url'])->findOrEmpty();
                $mhm_split  = app(SchoolSplitConfig::class)->getSplitConfig($course->mhm_id);
                $config     = count($mhm_split) ? $mhm_split : SystemConfig::get('split.config', []);
                $max_profit = round($course->price * ($config['distributor_first'] + $config['share']) / 100, 2);
                // 分享信息
                $data = [
                    'cover_url'      => $course->cover_url,
                    'course_title'   => $course->title,
                    'scribing_price' => $course->scribing_price,
                    'course_price'   => $course->price,
                    'max_profit'     => $max_profit,
                    'teacher_avatar' => app(Teacher::class)->getTeacherAvatar($course->teacher_id),
                    'teacher_name'   => app(Teacher::class)->getTeacherName($course->teacher_id),
                    'mhm_title'      => app(School::class)->getSchoolTitle($course->mhm_id),
                    'share_url_h5'   => $host . $uri[$type],
                    'force_login'    => $share_config[$share_key] ?? 0,
                ];
                break;

            case 2:
                // $share_key  = 'topic';
                $topic = app(Topic::class)->where('id', $id)->with(['cover_url'])->findOrEmpty();

                // 分享信息
                $data = [
                    'cover_url'    => $topic->cover_url,
                    'topic_title'  => $topic->title,
                    'mhm_title'    => app(School::class)->getSchoolTitle($topic->mhm_id),
                    'share_url_h5' => $host . $uri[$type],
                ];

                break;

            default:
                $data = [];
                break;
        }

        $data['share_code']  = $share_code;
        $data['open_device'] = ['app', 'pc', 'h5'];
        // $data['force_login'] = $share_config[$share_key]??0;

        $exist = app(ShareCode::class)->whereCode($share_code)->findOrEmpty();
        if ($exist->isEmpty()) {
            $res = ShareCode::create([
                                         'code'  => $share_code,
                                         'param' => [
                                             'type' => $type,
                                             'id'   => $id,
                                             'mid'  => $mid,
                                         ]
                                     ]);
            if ($res->isEmpty()) throw new LogicException('获取失败');
        }

        return $data;
    }

    /**
     * 生成短字符
     */
    public function shortStr($str): string
    {
        $code = floatval(sprintf('%u', crc32($str)));
        $sStr = '';
        while ($code) {
            $mod = fmod($code, 62);
            if ($mod > 9 && $mod <= 35) {
                $mod = chr($mod + 55);
            } else if ($mod > 35) {
                $mod = chr($mod + 61);
            }
            $sStr .= $mod;
            $code = floor($code / 62);
        }
        return $sStr;
    }

    public function filterSensitive($content, $resourceId, $type = 'comment'): string
    {
        // 构建敏感词库树
        $data     = app(Sensitive::class)->where('status', 1)->order('update_time', 'DESC')->column('title', 'id');
        $wordData = array_values($data);// 敏感词库
        if (!count($wordData)) return $content;

        $handle = SensitiveHelper::init()->setTree($wordData);
        // 检测是否含有敏感词
        $islegal = $handle->islegal($content);
        // 敏感词替换为***为例
        $filterContent = $handle->replace($content, '***');
        //标记敏感词
        // $markedContent = $handle->mark($content, '<mark>', '</mark>');
        // 获取内容中所有的敏感词
        $sensitiveWordGroup = $handle->getBadWord($content);
        // 敏感词替换记录
        if ($sensitiveWordGroup) {
            $sensitiveWord = array_values(array_unique($sensitiveWordGroup));
            $sids          = [];
            $title         = '';
            if ($sensitiveWord) {
                foreach ($sensitiveWord as $sw) {
                    $sids  = array_merge($sids, array_keys($data, $sw));
                    $title .= $sw . ',';
                }
                if ($sids && $title) {
                    Db::startTrans();
                    try {
                        // 记录数据
                        $insert = [
                            'mhm_id'      => request()->mhm_id,
                            'title'       => ',' . $title,
                            'content'     => $content,
                            'user_id'     => request()->mid,
                            'resource_id' => $resourceId,
                            'type'        => $type,
                            'create_time' => Request::time(),
                            'update_time' => Request::time(),
                        ];
                        $mod    = app(SensitiveRecord::class);
                        if (!$mod->insert($insert)) throw new LogicException('操作失败');

                        // 增加敏感词统计
                        $re = app(Sensitive::class)->where('id', 'IN', $sids)->inc('num')->update();
                        if (!$re) throw new LogicException('操作失败');

                        Db::commit();
                    } catch (LogicException $e) {
                        Db::rollback();
                        throw new LogicException($e->getMessage());
                    }
                }
            }
        }

        return $filterContent;
    }

    /**
     * shareSignature
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/09/08
     *
     * @param $url
     * @return mixed
     */
    public function shareSignature($url)
    {
        $share = new Share();
        return $share->getSignature($url);
    }
}
